package org.jadelyre.core.worker;

import org.jadelyre.core.task.EntryQueue;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

public abstract class Worker<T> {

    protected ThreadPoolExecutor executor;
    protected EntryQueue<T> entryQueue;
    protected int threshold = 10;//是否需要添加新task的阀值
    protected AtomicInteger taskCount = new AtomicInteger();
    private volatile boolean terminated = false;

    public Worker(ThreadPoolExecutor executor, EntryQueue<T> entryQueue) {
        this.executor = executor;
        this.entryQueue = entryQueue;
    }

    public void work(T t) {
        entryQueue.addEntry(t);
        if (taskCount.get() == 0) {
            //没有执行的task,添加
            taskCount.getAndIncrement();
            execute();
            return;
        }
        int count = entryQueue.getCount();
//        System.out.println(count);
        if (count >= threshold) {
            //超过阀值，添加新的task
            taskCount.getAndIncrement();
            execute();
            return;
        }
    }

    public void shutdown() {
        executor.shutdown();
    }

    protected abstract void execute();

    public AtomicInteger getTaskCount() {
        return taskCount;
    }

    public EntryQueue<T> getEntryQueue() {
        return entryQueue;
    }

    public boolean isTerminated() {
        return terminated;
    }

    public void setTerminated(boolean terminated) {
        this.terminated = terminated;
    }
}
